package com.devops.admin.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;

/**
 * @ClassName CorsFilterConfig
 * @Description TODO
 * @Author hepingguo
 * @Date 2022/4/24 17:13
 * @Version 1.0
 **/
@Configuration
public class CorsFilterConfig {

    /**
     * 开启跨域访问拦截器
     *
     */
    @Bean
    public CorsFilter corsFilter() {
        //创建CorsConfiguration对象后添加配置
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOriginPattern("*");
        //放行哪些请求方式
        //是否发送Cookie
        config.setAllowCredentials(true);
        config.setAllowedMethods(Arrays.asList("GET","PUT","POST","DELETE"));
        config.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type","X-Requested-With"));

        //2. 添加映射路径
        UrlBasedCorsConfigurationSource corsConfigurationSource =
                new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**", config);
        //返回CorsFilter
        return new CorsFilter(corsConfigurationSource);
    }
}
